#include "std/WJS_String.h"


WJS_String::WJS_String(char* pChars)
{
	m_LocalCh[0]='\0';
	m_pExtenChars=0;
	m_ExtenSize=0;
	m_bUseLocal=true;

	if(!pChars)
	{
		m_size=0;
		return;
	}

	m_size=strlen(pChars);
	if(m_size>0)
	{
		if(m_size<LOCALNUM)
		{
			m_bUseLocal=true;
			memcpy(m_LocalCh,pChars,sizeof(char)*(m_size+1));
		}
		else
		{
			m_bUseLocal=false;
			m_pExtenChars=new char[m_size+1];
			memcpy(m_pExtenChars,pChars,sizeof(char)*(m_size+1));
			m_ExtenSize=m_size;
		}
	}


}

WJS_String::~WJS_String()
{
	if(m_pExtenChars)
	{
		delete [] m_pExtenChars;
		m_pExtenChars=0;
	}
}

const char* WJS_String::c_str()
{
	if(m_bUseLocal)
		return m_LocalCh;
	else
		return m_pExtenChars;
}
bool WJS_String::append_Local(const char* pChars,int size)
{
	if(m_size+size<LOCALNUM)
	{
		memcpy(&m_LocalCh[m_size],pChars,sizeof(char)*size);
		if(m_size>0)
		{
			m_size+=size-1;
		}
		else
		{
			m_size=size;
		}
		return true;
	}

	return false;

}
void WJS_String::append_Extern(const char* pChars,int size)
{
	if(m_bUseLocal)
	{
		m_bUseLocal=false;

		if(m_size+size<m_ExtenSize)
		{
			memcpy(&m_pExtenChars,m_LocalCh,sizeof(char)*m_size);
			memcpy(&m_pExtenChars[m_size],pChars,sizeof(char)*size);
		}
		else
		{
			char * pExtenChars=new char[m_size+size];
			if(m_size>0)
				memcpy(pExtenChars,m_LocalCh,sizeof(char)*m_size);

			memcpy(&pExtenChars[m_size],pChars,sizeof(char)*size);
			if(m_pExtenChars)
				delete [] m_pExtenChars;	
			m_pExtenChars=pExtenChars;
			m_ExtenSize=m_size+size;
		}


	}
	else
	{
		if(m_size+size<m_ExtenSize)
		{
			memcpy(&m_pExtenChars[m_size],pChars,sizeof(char)*size);
		}
		else
		{
			char * pExtenChars=new char[m_size+size];
			if(m_size>0)
				memcpy(pExtenChars,m_pExtenChars,sizeof(char)*m_size);
			memcpy(&pExtenChars[m_size],pChars,sizeof(char)*size);
			if(m_pExtenChars)
				delete [] m_pExtenChars;	
			m_pExtenChars=pExtenChars;
			m_ExtenSize=m_size+size;
		}
	}

	if(m_size>0)
	{
		m_size+=size-1;
	}
	else
	{
		m_size=size;
	}

}
void WJS_String::append(const char* pChars)
{
	int size=strlen(pChars)+1;
	if(size>0)
	{
		//m_pCall0.ExcuteCallBack();
		if(m_bUseLocal)
		{
			if(append_Local(pChars,size))
				return;
		}

		append_Extern(pChars,size);

	}

}
